import {Component, OnInit, ViewChild} from '@angular/core';
import {MatDialog, MatPaginator, MatSnackBar, MatSort, MatTableDataSource} from '@angular/material';
import {Washer} from '../shared/washer.model';
import {WasherService} from '../shared/washer.service';
import {Router} from '@angular/router';
import {ConfirmDialogComponent} from '../../core/confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-washer-list',
  templateUrl: './washer-list.component.html',
  styleUrls: ['./washer-list.component.css']
})
export class WasherListComponent implements OnInit {
  displayedColumns = ['detail', 'name', 'identityId', 'gender', 'mobile', 'level', 'busy', 'oper'];
  dataSource: MatTableDataSource<Washer>;
  washers: Washer[] = [];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private washerService: WasherService, private router: Router, private snackBar: MatSnackBar,
              private dialog: MatDialog) { }

  ngOnInit() {
    this.washerService.getWasherList().subscribe((value) => {
      this.washers = <Washer[]><any>value;
      this.dataSource = new MatTableDataSource<Washer>(this.washers);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });
  }
  onDeleteClicked(target, row) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.washerService.currentWasher = row;
        const washerId = this.washerService.currentWasher.id;
        this.washerService.deleteWasher(String(washerId)).subscribe( value => {
          if (value) {
            const index = this.washers.findIndex( elem => elem.id === washerId);
            this.dataSource.data.splice(index, 1);
            this.refreshTable();
            this.openSnackBar('客户已删除！', '');
          } else {
            this.openSnackBar('删除客户失败！', '');
          }
        });
      }
    });
  }
  onAddClick(target) {
    this.router.navigate(['washers/', -1]); // -1 means new washer.
  }
  selectRow(target, row) {
    this.washerService.currentWasher = row;
    this.router.navigate(['washers/', row.id]);
  }
  private refreshTable() {
    this.dataSource.filter = '1';
    this.dataSource.filter = '';
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
